package mspbots.data.sync.rippling.receivers;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.data.sync.BaseReceiver;
import mspbots.data.sync.ResultMessageModel;
import mspbots.data.sync.rippling.model.RipplingDepartments;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.Optional;

/**
 * @author Jay Yang
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class RipplingDepartmentsReceiver extends BaseReceiver {

    @RabbitListener(queues = "rippling.departments.sync")
    public void processDepartments(ResultMessageModel model) {
        log.debug("processDepartments[rippling.departments.sync] ResultMessageModel {}", model);
        if (ResultMessageModel.MessageModelAction.ADD.equals(model.getAction())) {
            JsonNode fieldNode = model.getEntity();
            RipplingDepartments departments = this.objectMapper.convertValue(fieldNode, RipplingDepartments.class);
            departments.setExtend(fieldNode);
            departments.setTenantId(model.getTenantId());
            departments.setSyncTime(model.getSendTime());

            Optional<Long> id = this.databaseClient.execute("select id from rippling_departments " +
                    "where tenant_id =:tenantId and other_id =:otherId")
                    .as(Long.class)
                    .bind("tenantId", departments.getTenantId())
                    .bind("otherId", departments.getOtherId())
                    .fetch().one().blockOptional(Duration.ofSeconds(10));

            if (id.isPresent() && id.get() > 0) {
                departments.setId(id.get());
                this.databaseClient.update().table(RipplingDepartments.class).using(departments).fetch().rowsUpdated().subscribe();
            } else {
                this.databaseClient.insert().into(RipplingDepartments.class).using(departments).fetch().rowsUpdated().subscribe();
            }
        }
    }
}
